package grpc

import (
	"base_server/internal/models/cutpart"
	"base_server/internal/models/fabric"
	"context"
	"errors"
	"strings"

	"jihe.common/protos/base_server/proto"
)

func (s *Server) BaseCreateFabric(ctx context.Context, req *proto.BaseFabric) (ret *proto.BaseNull, err error) {
	fabricTbl := fabric.NewModel(s.Pgsql.Get())
	return fabricTbl.Create(req)
}

func (s *Server) BaseUpdateFabric(ctx context.Context, req *proto.BaseFabric) (ret *proto.BaseNull, err error) {
	fabricTbl := fabric.NewModel(s.Pgsql.Get())
	return fabricTbl.Update(req)
}

func (s *Server) BaseGetDetailFabric(ctx context.Context, req *proto.BaseFabric) (ret *proto.BaseFabric, err error) {
	fabricTbl := fabric.NewModel(s.Pgsql.Get())
	return fabricTbl.GetDetail(req.Id)
}

func (s *Server) BaseGetListFabric(ctx context.Context, req *proto.BaseGetListFabricReq) (ret *proto.BaseGetListFabricRes, err error) {
	fabricTbl := fabric.NewModel(s.Pgsql.Get())
	return fabricTbl.GetList(req)
}

func (s *Server) BaseGetFashionFabrics(ctx context.Context, req *proto.BaseGetFashionFabricsReq) (ret *proto.BaseFabrics, err error) {
	ret = new(proto.BaseFabrics)
	cutpartTbl := cutpart.NewModel(s.Pgsql.Get())
	cutParts, err := cutpartTbl.GetListByFashionId(req.FashionId)
	if err != nil {
		return
	}
	fabricIdMap := make(map[string]int)
	for _, v := range cutParts {
		if v.FabricIds != "" {
			fabricIdsArr := strings.Split(v.FabricIds, ",")
			for _, fid := range fabricIdsArr {
				fabricIdMap[fid] = 1
			}
		}
	}
	if len(fabricIdMap) != 0 {
		fids := make([]string, 0)
		for fid, _ := range fabricIdMap {
			fids = append(fids, fid)
		}
		fabricTbl := fabric.NewModel(s.Pgsql.Get())
		ret.List, err = fabricTbl.GetListByIds(fids)
		return
	}
	return
}

func (s *Server) BaseDeleteFabric(ctx context.Context, req *proto.BaseFabric) (ret *proto.BaseNull, err error) {
	ret = new(proto.BaseNull)
	fabricTbl := fabric.NewModel(s.Pgsql.Get())
	cutpartTbl := cutpart.NewModel(s.Pgsql.Get())
	if cutpartTbl.ExistByfabric(req.Id) {
		err = errors.New("errorno=1")
		return
	}
	err = fabricTbl.Delete(req)
	return
}
